package com.xjh.o2o.service.impl;

import java.io.File;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xjh.o2o.dao.ShopDao;
import com.xjh.o2o.dto.ShopExecution;
import com.xjh.o2o.entity.Shop;
import com.xjh.o2o.enums.ShopStateEnum;
import com.xjh.o2o.exceptions.ShopOperationException;
import com.xjh.o2o.service.ShopService;
import com.xjh.o2o.until.ImageUtil;
import com.xjh.o2o.until.PathUtil;


@Service
public class ShopServiceImpl implements ShopService{
	
	@Autowired
	private ShopDao shopDao;
	
	
	/**
	 * 保存店铺信息
	 */
	@Override
	@Transactional
	public ShopExecution addShop(Shop shop, File file) {
		//空值判断
		if(shop==null){
			return new ShopExecution(ShopStateEnum.NULL_SHOP);
		}
		try {
			//添加赋值 初始值
			shop.setEnableStatus(1);
			shop.setCreateTime(new Date());
			shop.setLastEditTime(new Date());
			//添加店铺信息
			int  effectedNum=shopDao.insertShop(shop);
			if(effectedNum <=0){
				throw new ShopOperationException("店铺创建失败");
			}else{
				if(file !=null){
					//存储图片
					try {
						addShopImg(shop,file);
					} catch (Exception e) {
						throw new ShopOperationException("addShopImg error :"+e.getMessage());
					}
					//更新店铺图片地址
					 effectedNum=shopDao.insertShop(shop);
					 if(effectedNum <=0){
							throw new ShopOperationException("更新图片地址失败");
						}
				}
			}
			
		} catch (Exception e) {
			throw new ShopOperationException("addShope error"+e.getMessage());
		}
		
		return new  ShopExecution(ShopStateEnum.CHECK,shop);
	}

	private void addShopImg(Shop shop, File file) {
		// 获取shop图片目录的相对值路径
		String dest = PathUtil.getShopImagePath(shop.getShopId());
		String shopImgAddr=ImageUtil.generateThumbnail(file, dest);
		shop.setShopImg(shopImgAddr);
				
	}
	

}
